package org.x.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.x.common.web.exception.BusinessException;
import org.x.user.mapper.SysMenuMapper;
import java.lang.Boolean;
import java.lang.Override;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.x.user.entity.SysMenu;
import org.x.user.dto.MenuDTO;
import org.x.user.query.MenuQuery;
import org.x.user.service.MenuService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.x.user.vo.MenuTreeVO;

import static org.x.common.base.result.ResultCode.MENU_NAME_EXIST;
import static org.x.common.base.result.ResultCode.MENU_NOT_FOUND;

/**
 * 菜单管理的实现
 *
 * @author 夏包包
 * @date 2025-03-08 13:39:03
 */
@Service
public class MenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements MenuService {

    @Autowired
    private SysMenuMapper menuMapper;

    @Override
    public Boolean addMenu(MenuDTO menuDTO) {
        QueryWrapper<SysMenu> queryWrapper = Wrappers.query(new SysMenu()).eq("menu_name", menuDTO.getMenuName());
        if (menuMapper.selectOne(queryWrapper) != null) {
            // 菜单名称已存在
            throw new BusinessException(MENU_NAME_EXIST);
        }
        SysMenu menuDO = new SysMenu();
        menuDO.setMenuName(menuDTO.getMenuName());
        menuDO.setParentId(menuDTO.getParentId());
        menuDO.setMenuUrl(menuDTO.getMenuUrl());
        menuDO.setMenuDesc(menuDTO.getMenuDesc());
        menuDO.setTenantId(menuDTO.getTenantId());
        menuDO.setMenuType(menuDTO.getMenuType());
        menuDO.setPath(menuDTO.getPath());
        menuDO.setComponent(menuDTO.getComponent());
        menuDO.setIcon(menuDTO.getIcon());
        menuDO.setPermId(menuDTO.getPermId());
        menuDO.setSort(menuDTO.getSort());
        menuDO.setHidden(menuDTO.getHidden());
        int result = menuMapper.insert(menuDO);
        return result > 0;
    }

    @Override
    public Boolean deleteMenu(MenuDTO menuDTO) {
        SysMenu menuDO = menuMapper.selectById(menuDTO.getMenuId());
        if (menuDO == null) {
            // 菜单不存在
            throw new BusinessException(MENU_NOT_FOUND);
        }
        int result = menuMapper.deleteById(menuDTO.getMenuId());
        return result > 0;
    }

    @Override
    public Boolean updateMenu(MenuDTO menuDTO) {
        SysMenu menuDO = menuMapper.selectById(menuDTO.getMenuId());
        if (menuDO == null) {
            // 菜单不存在
            throw new BusinessException(MENU_NOT_FOUND);
        }
        menuDO.setMenuName(menuDTO.getMenuName());
        menuDO.setParentId(menuDTO.getParentId());
        menuDO.setMenuUrl(menuDTO.getMenuUrl());
        menuDO.setMenuDesc(menuDTO.getMenuDesc());
        menuDO.setTenantId(menuDTO.getTenantId());
        menuDO.setMenuType(menuDTO.getMenuType());
        menuDO.setPath(menuDTO.getPath());
        menuDO.setComponent(menuDTO.getComponent());
        menuDO.setIcon(menuDTO.getIcon());
        menuDO.setPermId(menuDTO.getPermId());
        menuDO.setSort(menuDTO.getSort());
        menuDO.setHidden(menuDTO.getHidden());
        int result = menuMapper.updateById(menuDO);
        return result > 0;
    }

    @Override
    public SysMenu getMenuInfo(MenuQuery menuQuery) {
        SysMenu menuDO = menuMapper.selectById(menuQuery.getMenuId());
        if (menuDO == null) {
            throw new BusinessException(MENU_NOT_FOUND);
        }
        return menuDO;
    }

//    @Override
//    public List<MenuClosureDO> getMenuClosure(MenuQuery menuQuery) {
//        QueryWrapper<MenuClosureDO> queryWrapper = Wrappers.query(new MenuClosureDO()).eq("ancestor", menuQuery.getMenuId());
//        List<MenuClosureDO> menuClosureList = menuMapper.selectByAncestor(queryWrapper);
//        if (menuClosureList.isEmpty()) {
//            throw new BusinessException(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
//        }
//        return menuClosureList;
//    }

    /**
     * 查询树形结构的菜单
     * @return
     */

    @Override
    public List<MenuTreeVO> getMenuTree() {
        List<SysMenu> menuList = menuMapper.selectList(null);
        return buildTree(convertToVO(menuList), "0");
    }

    private List<MenuTreeVO> buildTree(List<MenuTreeVO> voList, String parentId) {
        List<MenuTreeVO> tree = new ArrayList<>();
        for (MenuTreeVO vo : voList) {
            if (parentId.equals(vo.getParentId())) {
                vo.setChildren(buildTree(voList, vo.getId()));
                tree.add(vo);
            }
        }
        // 按sort字段排序（根据实际字段类型调整）
        tree.sort(Comparator.comparingInt(MenuTreeVO::getSort));
        return tree;
    }

    private List<MenuTreeVO> convertToVO(List<SysMenu> menus) {
        return menus.stream().map(menu -> {
            MenuTreeVO vo = new MenuTreeVO();
            BeanUtils.copyProperties(menu, vo); // 需要导入Spring BeanUtils
            vo.setChildren(new ArrayList<>()); // 初始化空列表
            return vo;
        }).collect(Collectors.toList());
    }
}
